package 行为型模式


/**
 * 将一个请求封装为一个对象，从而使你可用不同的请求对客户进行参数化，
 * 对请求排队或记录请求日志，以及支持可撤销的操作。
 */

class TextEditor {
    private val buffer = StringBuilder()

    fun copy() {

    }

    fun paste() {
        getFromClipBoard().also { add(it) }
    }

    private fun getFromClipBoard(): String {
        return "123"
    }

    fun add(s: String) {
        buffer.append(s)
    }

    fun delete() {
        if (buffer.isNotEmpty()) {
            buffer.deleteCharAt(buffer.lastIndex)
        }
    }

    fun getState(): String {
        return buffer.toString()
    }
}

interface Command {
    fun execute()
}

class CopyCommand(private val receiver: TextEditor) : Command {
    override fun execute() {
        receiver.copy()
    }

}

class PasteCommand(private val receiver: TextEditor) : Command {
    override fun execute() {
        receiver.paste()
    }

}

fun main() {
    val editor = TextEditor()
    editor.add("Command pattern in text editor.\n")
    // 执行一个CopyCommand:
    // 执行一个CopyCommand:
    val copy: Command = CopyCommand(editor)
    copy.execute()
    editor.add("----\n")
    // 执行一个PasteCommand:
    // 执行一个PasteCommand:
    val paste: Command = PasteCommand(editor)
    paste.execute()
    println(editor.getState())
}